package com.smartlazy.sequence.redis.core.sequence;

import com.smartlazy.sequence.core.sequence.Sequence;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 序列号区间生成器接口默认实现
 * @author howe
 */
public class RedisSequence implements Sequence {

    /**
     * 获取区间是加一把独占锁防止资源冲突
     */
    private final Lock lock = new ReentrantLock();

    @Resource
    private RedisTemplate<String, Long> redisTemplate;

    /**
     * 需要获取区间的业务名称
     */
    private String name;

    @Override
    public long nextValue() throws Exception {
        lock.lock();
        try {
            return redisTemplate.opsForValue().increment(this.name, 1);
        } catch (Exception e) {
            throw new Exception(e);
        } finally {
            lock.unlock();
        }
    }

    public void setName(String name) {
        this.name = name;
    }
}
